package test4;

/**
 * @Author Jun jie Yi
 * 2022/5/1 23:31
 */
public class NumMatrix {
    int[][] sum;

    public static void main(String[] args) {
        int[][] matrix = {
                {3, 0, 1, 4, 2},
                {5, 6, 3, 2, 1},
                {1, 2, 0, 1, 5},
                {4, 1, 0, 1, 7},
                {1, 0, 3, 0, 5}
        };
        int[][] arr = {{2, 1, 4, 3}, {1, 1, 2, 2}, {1, 2, 2, 4}};
        NumMatrix numMatrix = new NumMatrix(matrix);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(numMatrix.sumRegion(arr[i][0], arr[i][1], arr[i][2], arr[i][3]));
        }
    }

    public NumMatrix(int[][] matrix) {
        sum = new int[matrix.length + 1][matrix[0].length + 1];
        for (int i = 1; i < sum.length; i++) {
            for (int j = 1; j < sum[0].length; j++) {
                sum[i][j] = matrix[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1];
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        return sum[row2 + 1][col2 + 1] - sum[row1][col2 + 1] - sum[row2 + 1][col1] + sum[row1][col1];
    }
}
